package com.linkallcloud.core.vo;

import java.io.Serializable;
import java.time.Duration;
import java.time.Instant;

import com.linkallcloud.core.lang.Strings;
import com.linkallcloud.core.security.ICage;
import com.linkallcloud.deapi.DeApiException;
import com.linkallcloud.deapi.tuils.Encrypts;

public class OnlineUser implements ICage, Serializable {
    private static final long serialVersionUID = 5038783830124399329L;

    private String appCode;

    private String loginName;

    private String token;

    private long loginTime;
    private int timeout;// unit minutes
    private long logoutTime;

    public OnlineUser() {
        super();
    }

    public OnlineUser(String appCode, String loginName, String token, Duration duration) {
        super();
        this.appCode = appCode;
        this.loginName = loginName;
        this.token = token;

        this.loginTime = Instant.now().toEpochMilli();
        this.timeout = duration != null ? (int) duration.toMinutes() : 10;

    }

    public OnlineUser(String loginName, double loginTime) {
        super();
        this.loginName = loginName;
        this.loginTime = (long) loginTime;// (new Double(loginTime)).longValue();
    }

    public OnlineUser(String appCode, String loginName, long logoutTime) {
        super();
        this.appCode = appCode;
        this.loginName = loginName;
        this.logoutTime = logoutTime;
    }

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public long getLoginTime() {
        return loginTime;
    }

    public void setLoginTime(long loginTime) {
        this.loginTime = loginTime;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public long getLogoutTime() {
        return logoutTime;
    }

    public void setLogoutTime(long logoutTime) {
        this.logoutTime = logoutTime;
    }

    public String getAppCode() {
        return appCode;
    }

    public void setAppCode(String appCode) {
        this.appCode = appCode;
    }

    @Override
    public void dataMasking(String nonce) {
        this.token = null;
    }

    @Override
    public void reenforce(String nonce) {
        if (!Strings.isBlank(nonce)) {
            try {
                this.token = Encrypts.encryptAES(this.token, nonce);
            } catch (DeApiException e) {
                this.token = null;
            }
        } else {
            this.token = null;
        }
    }

}
